"use client";

import {
  createContext,
  useContext,
  ReactNode,
  useState,
  useEffect,
} from "react";

// 简化的类型定义
interface Message {
  id: string;
  type: 'human' | 'assistant' | 'ai';
  content: Array<{ type: 'text'; text: string }>;
}

interface Thread {
  thread_id: string;
  title?: string;
}

interface StateType {
  messages: Message[];
}

// 简化的Stream接口
interface SimpleStreamValue {
  messages: Message[];
  isLoading: boolean;
  error: Error | null;
  values: any;
  submit: (options: { input: any; streamMode?: string }) => Promise<void>;
  stop: () => void;
  interrupt: null;
  getMessagesMetadata: () => null;
}

interface StreamContextType {
  stream: SimpleStreamValue;
  client: any;
  setThreadId: (id: string | null) => void;
  threadId: string | null;
  setThreads: (threads: Thread[]) => void;
  threads: Thread[];
  assistantId: string;
  values: { ui?: any[] };
}

const StreamContext = createContext<StreamContextType | undefined>(undefined);

export function useStreamContext() {
  const context = useContext(StreamContext);
  if (context === undefined) {
    throw new Error("useStreamContext must be used within a StreamProvider");
  }
  return context;
}

function StreamSession({
  apiUrl,
  apiKey,
  assistantId,
  threadId,
  setThreadId,
  setThreads,
  getThreads,
}: {
  apiUrl: string;
  apiKey?: string;
  assistantId: string;
  threadId: string | null;
  setThreadId: (id: string | null) => void;
  setThreads: (threads: Thread[]) => void;
  getThreads: () => Promise<Thread[]>;
}): StreamContextType {
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const safeThreadId = threadId || `thread_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;

  console.log("=== StreamSession 简化版配置 ===", {
    apiUrl: apiUrl,
    assistantId: assistantId,
    threadId: safeThreadId
  });

  // 加载历史消息
  const loadHistoryMessages = async (tid: string) => {
    try {
      console.log("🔍 加载线程历史消息:", tid);
      const response = await fetch(`${apiUrl}/threads/${tid}/history`);
      if (response.ok) {
        const data = await response.json();
        console.log("📚 获取到历史消息:", data);
        
        if (data.messages && Array.isArray(data.messages)) {
          const historyMessages: Message[] = data.messages.map((msg: any) => ({
            id: msg.id || `history_${Date.now()}_${Math.random()}`,
            type: msg.type === 'user' ? 'human' : (msg.type === 'assistant' ? 'assistant' : msg.type),
            content: [{ type: 'text', text: msg.content || '' }]
          }));
          
          console.log("🔄 设置历史消息:", historyMessages.length);
          setMessages(historyMessages);
        }
      } else {
        console.log("⚠️ 无法获取历史消息:", response.status);
      }
    } catch (error) {
      console.error("❌ 加载历史消息失败:", error);
    }
  };

  // LangGraph的MemorySaver会自动处理历史消息，无需前端手动加载
  // useEffect(() => {
  //   if (threadId && threadId !== 'null' && messages.length === 0) {
  //     console.log("🔄 初始化加载历史消息");
  //     loadHistoryMessages(threadId);
  //   }
  // }, [threadId, apiUrl]);

  // 简化的submit函数
  const submit = async (options: { input: any; streamMode?: string }) => {
    try {
      setIsLoading(true);
      setError(null);

      console.log("=== 📤 开始发送请求 ===");
      console.log("选项:", options);
      console.log("当前线程ID:", threadId);
      
      // 使用safeThreadId确保始终有有效的threadId
      const currentThreadId = threadId || `thread_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
      console.log("实际使用的线程ID:", currentThreadId);
      
      // 如果threadId为空，通知上层组件更新threadId
      if (!threadId && setThreadId) {
        console.log("🔄 设置新的threadId:", currentThreadId);
        setThreadId(currentThreadId);
      }

      // 处理输入数据
      let inputText = '';
      if (typeof options.input === 'string') {
        inputText = options.input;
      } else if (options.input.messages && Array.isArray(options.input.messages)) {
        // 从复杂的消息结构中提取文本
        const lastMessage = options.input.messages[options.input.messages.length - 1];
        if (lastMessage && lastMessage.content && Array.isArray(lastMessage.content)) {
          inputText = lastMessage.content.map((c: any) => c.text || '').join(' ');
        }
      }

      console.log("提取的输入文本:", inputText);

      // 创建简化的用户消息
      const userMessage: Message = {
        id: `human_${Date.now()}`,
        type: 'human',
        content: [{ type: 'text', text: inputText }]
      };
      console.log("用户消息:", userMessage);
      
      // 立即添加用户消息到界面（乐观更新）
      setMessages(prev => {
        const newMessages = [...prev, userMessage];
        console.log("🔄 立即添加用户消息，总数:", newMessages.length);
        return newMessages;
      });

      const requestBody = {
        input: {
          messages: [userMessage]
        },
        config: {
          configurable: {
            thread_id: currentThreadId
          }
        },
        assistant_id: assistantId,
        stream_mode: [options.streamMode || 'values'] // 修复：使用数组
      };

      console.log("🚀 发送请求到:", `${apiUrl}/runs/stream`);
      console.log("📋 请求体:", JSON.stringify(requestBody, null, 2));
      console.log("🔗 当前线程ID:", currentThreadId);
      
      const response = await fetch(`${apiUrl}/runs/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(apiKey && { 'Authorization': `Bearer ${apiKey}` })
        },
        body: JSON.stringify(requestBody)
      });

      console.log("📡 响应状态:", response.status, response.statusText);
      console.log("响应头:", Object.fromEntries(response.headers.entries()));

      if (!response.ok) {
        const errorText = await response.text();
        console.error("❌ HTTP错误响应:", errorText);
        throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
      }

      console.log("✅ 响应OK，开始处理SSE流");
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      const decoder = new TextDecoder();
      let buffer = '';
      let eventCount = 0;

      console.log("🔄 开始读取SSE流...");
      let currentEvent = '';
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          console.log("✅ SSE流读取完成，总事件数:", eventCount);
          break;
        }

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('event: ')) {
            currentEvent = line.slice(7);
            console.log(`🎯 SSE事件类型: ${currentEvent}`);
          } else if (line.startsWith('data: ')) {
            eventCount++;
            const rawData = line.slice(6);
            console.log(`📡 收到SSE数据 #${eventCount} (${currentEvent}):`, rawData);
            
            try {
              const data = JSON.parse(rawData);
              console.log("解析后的数据:", data);

              if (currentEvent === 'values' && data.values?.messages) {
                console.log("🤖 处理AI消息:", data.values.messages);
                setMessages(prev => {
                  // 找到最新的AI回复（通常是数组中的最后一个assistant消息）
                  const aiMessages = data.values.messages.filter((msg: any) => 
                    msg.type === 'assistant' || msg.type === 'ai'
                  );
                  
                  if (aiMessages.length === 0) {
                    console.log("⚠️ 没有找到AI消息");
                    return prev;
                  }
                  
                  // 取最后一个AI消息
                  const latestAiMsg = aiMessages[aiMessages.length - 1];
                  console.log("📝 处理最新AI消息:", latestAiMsg);
                  
                  // 正确提取文本内容
                  let textContent = '';
                  if (Array.isArray(latestAiMsg.content)) {
                    textContent = latestAiMsg.content
                      .filter((item: any) => item.type === 'text')
                      .map((item: any) => item.text)
                      .join(' ');
                  } else if (typeof latestAiMsg.content === 'string') {
                    textContent = latestAiMsg.content;
                  }
                  
                  console.log("📄 提取的AI文本内容:", textContent);
                  
                  // 简化重复检查：只检查最后一条消息是否已经是相同的AI回复
                  const lastMsg = prev[prev.length - 1];
                  if (lastMsg && lastMsg.type === 'assistant' && lastMsg.content[0]?.text === textContent) {
                    console.log("⚠️ 最新AI消息已存在，跳过");
                    return prev;
                  }
                  
                  const aiMessage: Message = {
                    id: `ai_${Date.now()}_${Math.random()}`,
                    type: 'assistant',
                    content: [{ type: 'text', text: textContent }]
                  };
                  
                  const newMessages = [...prev, aiMessage];
                  console.log("✅ 添加新AI消息，总数:", newMessages.length);
                  return newMessages;
                });
              } else if (data.event === 'metadata') {
                console.log("📋 收到元数据:", data);
              } else if (data.event === 'end') {
                console.log("🏁 收到结束事件");
              } else {
                console.log("❓ 未知事件类型:", data.event);
              }
            } catch (e) {
              console.warn("⚠️ 解析SSE数据失败:", e, "原始数据:", rawData);
            }
          }
        }
      }
    } catch (err) {
      console.error("❌ 发送消息失败:");
      console.error("错误类型:", (err as any)?.constructor?.name);
      console.error("错误消息:", (err as any)?.message);
      console.error("完整错误:", err);
      setError(err as Error);
    } finally {
      console.log("🔄 设置加载状态为false");
      setIsLoading(false);
    }
  };

  const streamValue: SimpleStreamValue = {
    messages,
    isLoading,
    error,
    values: {},
    submit,
    stop: () => console.log("停止流"),
    interrupt: null,
    getMessagesMetadata: () => null
  };

  const client = null; // 暂时不使用LangGraph SDK

  return {
    stream: streamValue,
    client,
    setThreadId,
    threadId: safeThreadId,
    setThreads,
    threads: [],
    assistantId,
    values: { ui: [] }
  };
}

// Default values for the form - 直接连接后端
const DEFAULT_API_URL = "http://localhost:2024";  // 直接连接后端
const DEFAULT_ASSISTANT_ID = "chatbot";

// 工具函数
function getApiKey(): string | null {
  if (typeof window === 'undefined') return null;
  return window.localStorage.getItem("lg:chat:apiKey");
}

export const StreamProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const [threadId, setThreadId] = useState<string | null>(null);
  const [threads, setThreads] = useState<Thread[]>([]);

  // Mock getThreads function
  const getThreads = async (): Promise<Thread[]> => {
    try {
      // 这里可以实现真正的getThreads逻辑
      return [];
    } catch (error) {
      console.error("获取threads失败:", error);
      return [];
    }
  };

  // 使用默认配置
  const apiUrl = DEFAULT_API_URL;
  const assistantId = DEFAULT_ASSISTANT_ID;
  const apiKey = "";

  console.log("Stream Provider 简化版配置:", {
    apiUrl,
    assistantId
  });

  return (
    <StreamContext.Provider value={StreamSession({
      apiUrl,
      apiKey,
      assistantId,
      threadId,
      setThreadId,
      setThreads,
      getThreads
    })}>
      {children}
    </StreamContext.Provider>
  );
};
